1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| const imgReg = /<img.*?(?:>|\/>)/gi; const imgStr = code.match(imgReg) if (imgStr && imgStr.length) { getImgUrl(imgStr, code) }
function getImgBase64(url, filename, base64Callback) { const imgType = ['jpg', 'jpeg', 'png', 'bmp', 'gif'] const img = new Image img.src = url img.onload = function(){ const { width, height } = img let canvas = document.createElement('canvas') const ctx = canvas.getContext('2d') canvas.width = width canvas.height = height ctx.drawImage(img, 0, 0, width, height) const imgTypeStr = img.src.split('.').pop().toLowerCase() const ext = imgType.includes(imgTypeStr) ? imgTypeStr.toUpperCase() : 'JPG' console.log(ext) const base64 = canvas.toDataURL(`image/${ext}`) base64Callback(base64, filename) canvas = null } }
function getImgUrl(imgStr, code, host = '') { const hostStr = host || window.location.host console.log(hostStr) const imgSrc = [] const srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i imgStr.forEach(i => { if (! i.includes(hostStr) && ! i.includes('data:image')) { imgSrc.push(i.match(srcReg)) } }) getImgBase64('https://hbimg.huabanimg.com/49d8b53f48fcaa8cc5694899a66d1051340b74c68b75e-hBqQmm_fw658/format/webp', 'lancema', getBase64Callback) }
function getBase64ToFile(base64, filename) { const arr = base64.split(',') const mime = arr[0].match(/:(.*?);/)[1] const bstr = atob(arr[1]) let n = bstr.length const u8arr = new Uint8Array(n) while(n--){ u8arr[n] = bstr.charCodeAt(n) } return new File([u8arr], filename, { type: mime }) } function getBase64Callback(base64, filename) { console.log(getBase64ToFile(base64, filename)) }
|